<template>
  <div id="shopcar">
    <div id="content">
      <div class="header">
        <img src="./../../common/img/logo-round.png" class="header_logo" />
        <span>购物车</span>
      </div>
      <div class="cont_title">
        <span>全部商品</span>
      </div>
      <div class="cont_op" v-if="cartgoods.length">
        <div class="con_selet">
          <input type="checkbox" class="con_selectAll" :checked="isSelectedAll" @click.stop="selectedAll" />
          <label for="con_selectAll" class="all_select">全选</label>
        </div>
        <div class="op_text">商品信息</div>
        <div class="op_text">单价</div>
        <div class="op_text">数量</div>
        <div class="op_text">金额</div>
        <div class="op_text">操作</div>
      </div>
      <div class="pro_box" v-if="cartgoods.length">
        <div class="goods" v-for="(goods, index) in cartgoods" :key="index">
          <ul class="item_content">
            <li class="td td-chk">
              <input type="checkbox" class="checkBox" :checked="goods.checked" @click="singleSelected(goods)" />
            </li>
            <li class="td td-item">
              <div class="td-item-pic">
                <img :src="goods.thumb_url" />
              </div>
              <div class="td-item-info">{{ goods.goods_name }}</div>
            </li>
            <li class="td td-price"><strong>{{ goods.price | moneyFormat }}</strong></li>
            <li class="td td-amount">
              <el-input-number v-model="goods.buy_count" :min="1" :max="goods.counts"
                @change="handleGoodsCountChange(goods, goods.buy_count)"></el-input-number>
            </li>
            <li class="td td-sum"><strong>{{ goods.buy_count * goods.price | moneyFormat }}</strong></li>
            <li class="td td-op"><a @click="clickTrash(goods)">删除</a></li>
          </ul>
        </div>
      </div>
      <div class="pro_box empty-cart" v-else>
        <div class="showcard">
          <img src="./img/showcard.jpg" alt="" class="showcard_img">
          <div class="showcard_text">购物车里空空如也</div>
          <div class="showcard_next"><a href="http://localhost:8080/#/home" class="showcard_next_a">前往购物</a></div>
        </div>
      </div>
    </div>
    <div id="footer">
      <div class="foot_select">
        <input type="checkbox" class="foot_selectAll" name="foot_selectAll" :checked="isSelectedAll"
          @click.stop="selectedAll" />
        <label for="foot_selectAll" class="all_select">全选</label>
      </div>
      <div class="foot_op">
        <a class="foot_remove" @click.prevent="emptyCart">清空购物车</a>
      </div>
      <div class="foot_total">
        <div class="amout-sum">
          <span class="txt">已选商品</span>
          <strong id="selected_amout">{{ totalAmount }}</strong>
          <span class="txt">件</span>
        </div>
        <div class="price-sum">
          <span class="txt">合计（不含运费）：</span>
          <strong class="selected_price">{{ totalPrice | moneyFormat }}</strong>
        </div>
        <div class="btn-area">
          <a class="btn-sumbit" :class="{ 'btn-allow': totalAmount }" @click="moneyCount">结&nbsp;算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { MessageBox } from 'element-ui';
import { updateStock } from './../../api/index'; // Import the new API method

export default {
  data() {
    return {
      isSelectedAll: false,
      totalPrice: 0,  // 商品总价
      totalAmount: 0, // 已选商品
    }
  },
  computed: {
    ...mapState(['userInfo', 'cartgoods', 'orders']),
  },
  mounted() {
    let user_id = this.userInfo.id;
    // 请求商品数据
    this.$store.dispatch('reqCartsGoods', { user_id });
    this.computeShopCar();
  },
  methods: {
    ...mapActions(['reqCartsGoods', 'updateGoodsCount', 'selectedAll', 'singleSelected', 'delSingleGoods', 'delAllGoods', 'createOrder']),
    // 更新商品数量并重新计算购物车
    handleGoodsCountChange(goods, count) {
      let user_id = this.userInfo.id;
      this.updateGoodsCount({ goods, count, user_id });
      this.computeShopCar();
    },
    // 是否选中所有商品
    selectedAll() {
      this.isSelectedAll = !this.isSelectedAll;
      this.$store.dispatch('selectedAll', { isSelectedAll: this.isSelectedAll });
      this.cartgoods.forEach(goods => {
        goods.checked = this.isSelectedAll;
      });
      this.computeShopCar();
    },
    // 计算购物车商品总价和总数量
    computeShopCar() {
      let totalPrice = 0;
      let totalAmount = 0;
      this.cartgoods.forEach((goods) => {
        if (goods.checked) {
          totalPrice += goods.price * goods.buy_count;
          totalAmount += goods.buy_count;
        }
      });
      this.totalPrice = totalPrice;
      this.totalAmount = totalAmount;
    },
    // 单个商品的选中与否
    singleSelected(goods) {
      this.$store.dispatch('singleSelected', { goods });
      this.hasSelectedAll();
      this.computeShopCar();
    },
    // 判断是否全选
    hasSelectedAll() {
      let flag = true;
      this.cartgoods.forEach((goods) => {
        if (!goods.checked) {
          flag = false;
        }
      });
      this.isSelectedAll = flag;
    },
    // 删除单个商品
    clickTrash(goods) {
      this.$confirm('您确定删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let user_id = this.userInfo.id;
        this.delSingleGoods({ goods, user_id });
        this.computeShopCar();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除所有商品
    emptyCart() {
      this.$confirm('您确定删除所有商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let user_id = this.userInfo.id;
        this.delAllGoods({ user_id });
        this.computeShopCar();
        this.totalAmount = 0;
        this.totalPrice = 0;
        this.isSelectedAll = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 结算
    async moneyCount() {
      this.$confirm('您确定购买这些商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let user_id = this.userInfo.id;
        let selectedGoods = this.cartgoods.filter(goods => goods.checked);

        // 生成订单
        let order = {
          user_id: user_id,
          items: selectedGoods,
          totalAmount: this.totalAmount,
          totalPrice: this.totalPrice,
          date: new Date().toLocaleString()
        };
        await this.$store.dispatch('createOrder', order);

        // 更新库存
        for (let goods of selectedGoods) {
          await updateStock(goods.goods_id, goods.buy_count);
        }

        // 删除已购买商品
        selectedGoods.forEach(goods => {
          this.$store.dispatch('delSingleGoods', { goods, user_id });
        });

        this.$message({
          type: 'info',
          message: '购买成功！'
        });

        // 重置购物车状态
        this.totalAmount = 0; // 清零已选商品数量
        this.totalPrice = 0; // 清零总价
        this.isSelectedAll = false; // 重置全选框的状态

        // 清空选中的商品
        this.cartgoods.forEach(goods => {
          goods.checked = false;
        });

        // 重新计算购物车
        this.computeShopCar();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消购买'
        });
      });
    }
  }
}
</script>

<style scoped>
#shopcar {
  padding: 20px 20px 0 20px;
  background: #f9f9f9;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e6e6e6;
}

.header_logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.header span {
  font-size: 24px;
  font-weight: bold;
  margin-left: 20px;
}

.cont_title {
  margin: 20px 0;
  border-bottom: 2px solid #e6e6e6;
}

.cont_title span {
  display: inline-block;
  margin-bottom: 6px;
  font-size: 20px;
  color: #f40;
  padding-bottom: 5px;
  border-bottom: 2px solid #f40;
}

.cont_op {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #e6e6e6;
  font-weight: bold;
}

.op_text {
  width: 15%;
  text-align: center;
}

.pro_box {
  margin-top: 20px;
}

.goods {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background: #fff;
  margin-bottom: 15px;
}

.item_content {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}

.td-item {
  display: flex;
  align-items: center;
  width: 13%;
}

.td-item-pic img {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 20px;
}

.td-item-info {
  font-size: 16px;
}

.td-price,
.td-amount,
.td-sum,
.td-op {
  width: 13%;
  text-align: center;
}

.td-op a {
  color: #f40;
  cursor: pointer;
}

.td-op a:hover {
  color: #c00;
}

#footer {
  display: flex;
  align-items: center;
  margin-top: 80px;
  justify-content: space-between;
  padding: 10px 0;
  background: #f5f5f5;
  border-top: 1px solid #e6e6e6;
  position: sticky;
  bottom: 0;
  z-index: 1000;
}

.foot_select,
.foot_op,
.foot_total {
  display: flex;
  align-items: center;
}

.foot_remove {
  margin-left: 20px;
  cursor: pointer;
  color: #f40;
}

.foot_remove:hover {
  color: #c00;
}

.amout-sum,
.price-sum {
  margin-left: 20px;
}

.selected_price {
  font-size: 20px;
  font-weight: bold;
  color: #f40;
}

.btn-area {
  margin-left: 20px;
}

.btn-sumbit {
  padding: 10px 20px;
  background: #b0b0b0;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: not-allowed;
}

.btn-sumbit.btn-allow {
  background: #f40;
  cursor: pointer;
}

.showcard {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin-top: 50px;
}

.showcard_img {
  width: 300px;
  height: 300px;
}

.showcard_text {
  font-size: 20px;
  margin-top: 20px;
}

.showcard_next_a {
  display: inline-block;
  margin-top: 20px;
  text-decoration: none;
  color: red;
}

.showcard_next_a:hover {
  color: #f40;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .cont_op {
    display: none;
  }

  .goods {
    flex-direction: column;
    align-items: flex-start;
  }

  .item_content {
    flex-direction: column;
    width: 100%;
  }

  .td-item,
  .td-price,
  .td-amount,
  .td-sum,
  .td-op {
    margin-bottom: 10px;
    width: 100%;
    text-align: left;
  }

  .td-item {
    justify-content: space-between;
  }

  .td-price,
  .td-amount,
  .td-sum {
    justify-content: flex-end;
  }

  .td-op {
    justify-content: flex-start;
  }

  #footer {
    flex-direction: column;
    align-items: flex-start;
  }

  .foot_select,
  .foot_op,
  .foot_total {
    margin-bottom: 10px;
  }

  .btn-area {
    margin-left: 0;
  }
}

.all_select {
  margin-left: 5px;
  margin-top: 4px;
}
</style>
